package com.kujie.access.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kujie.access.domain.po.AccessEnterpriseRentalInformation;
import com.kujie.access.domain.po.AccessPolicySubmitInformation;
import com.kujie.access.domain.po.AccessTenantManagement;
import com.kujie.access.domain.query.TenantManageQuery;
import com.kujie.access.domain.vo.TenantManageVO;
import com.kujie.access.mapper.AccessEnterpriseRentalInformationMapper;
import com.kujie.access.mapper.AccessPolicySubmitInformationMapper;
import com.kujie.access.mapper.AccessTenantManagementMapper;
import com.kujie.access.service.IAccessTenantManagementService;
import com.kujie.access.service.ITenantManageService;
import com.kujie.common.core.exception.ServiceException;
import com.kujie.common.core.utils.StringUtils;
import com.kujie.common.excel.core.ExcelResult;
import com.kujie.common.excel.utils.ExcelUtil;
import com.kujie.common.mybatis.core.page.PageQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户管理 api
 *
 * @author jyy
 * @date 2025-05-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantManageServiceImpl implements ITenantManageService {
    private final AccessPolicySubmitInformationMapper accessPolicySubmitInformationMapper;
    private final AccessEnterpriseRentalInformationMapper accessEnterpriseRentalInformationMapper;
    private final AccessTenantManagementMapper accessTenantManagementMapper;
    private final IAccessTenantManagementService accessTenantManagementService;

    /**
     * 获取租户管理分页
     *
     * @param query     入参
     * @param pageQuery 分页入参
     * @return Page<TenantManageVO>
     */
    @Override
    public Page<TenantManageVO> getTenantManagePage(TenantManageQuery query, PageQuery pageQuery) {
        Page<TenantManageVO> result = pageQuery.build(new TenantManageVO());

        LambdaQueryWrapper<AccessTenantManagement> lqw = getAccessTenantManagementLambdaQueryWrapper(query);
        Page<AccessTenantManagement> page = accessTenantManagementMapper.selectPage(pageQuery.build(), lqw);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return result;
        }

        List<TenantManageVO> voList = page.getRecords().stream().map(item -> {
            TenantManageVO vo = new TenantManageVO();
            vo.setId(item.getId());
            vo.setCompanyUuid(item.getCompanyUuid());
            vo.setCompanyName(item.getCompanyName());
            vo.setCompanyLegelPerson(item.getCompanyLegelPerson());
            vo.setLegelPersonPhone(item.getLegelPersonPhone());
            vo.setLegelIdCard(item.getLegelIdCard());
            vo.setUnifiedSocialCreditIdentifier(item.getUnifiedSocialCreditIdentifier());
            vo.setAdministrativeContactPerson(item.getAdministrativeContactPerson());
            vo.setAdministrativeContactPersonPhone(item.getAdministrativeContactPersonPhone());
            vo.setIndustryType(item.getIndustryType());
            vo.setMainBusiness(item.getMainBusiness());
            vo.setEstablishedTime(item.getEstablishedTime());
            vo.setBusinessRegistrationAddress(item.getBusinessRegistrationAddress());
            vo.setActualOfficeAddress(item.getActualOfficeAddress());
            vo.setRemark(item.getRemark());
            return vo;
        }).toList();

        result.setRecords(voList);
        result.setTotal(page.getTotal());
        return result;
    }

    private static @NotNull LambdaQueryWrapper<AccessTenantManagement> getAccessTenantManagementLambdaQueryWrapper(TenantManageQuery query) {
        LambdaQueryWrapper<AccessTenantManagement> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(query.getCompanyName()), AccessTenantManagement::getCompanyName, query.getCompanyName());
        lqw.like(StringUtils.isNotEmpty(query.getCompanyLegelPerson()), AccessTenantManagement::getCompanyLegelPerson, query.getCompanyLegelPerson());
        return lqw;
    }

    /**
     * 新增租户管理
     *
     * @param query   入参
     * @param isValid 是否校验数据
     * @return int
     */
    @Override
    public int addTenantManage(TenantManageQuery query, boolean isValid) {
        if (isValid) {
            String companyName = query.getCompanyName();
            LambdaQueryWrapper<AccessTenantManagement> lqw = new LambdaQueryWrapper<>();
            lqw.eq(AccessTenantManagement::getCompanyName, companyName);
            List<AccessTenantManagement> poList = accessTenantManagementMapper.selectList(lqw);
            if (!CollectionUtils.isEmpty(poList)) {
                throw new ServiceException("单位名称已存在");
            }
        }

        AccessTenantManagement po = BeanUtil.toBean(query, AccessTenantManagement.class);
        po.setCompanyUuid(IdUtil.randomUUID());
        return accessTenantManagementMapper.insert(po);
    }

    /**
     * 修改租户管理
     *
     * @param query   入参
     * @param isValid 是否校验数据
     * @return int
     */
    @Override
    public int updateTenantManage(TenantManageQuery query, boolean isValid) {
        AccessTenantManagement po = BeanUtil.toBean(query, AccessTenantManagement.class);
        return accessTenantManagementMapper.updateById(po);
    }

    /**
     * 修改租户管理
     *
     * @param companyUuids     入参
     * @param isValid 是否校验数据
     * @return int
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteTenantManage(List<String> companyUuids, boolean isValid) {
        if (companyUuids == null) {
            return 0;
        }

        // 删除政策信息
        LambdaQueryWrapper<AccessPolicySubmitInformation> accessPolicySubmitInformationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        accessPolicySubmitInformationLambdaQueryWrapper.in(AccessPolicySubmitInformation::getCompanyUuid, companyUuids);
        accessPolicySubmitInformationMapper.delete(accessPolicySubmitInformationLambdaQueryWrapper);

        // 删除企业租赁信息
        LambdaQueryWrapper<AccessEnterpriseRentalInformation> accessEnterpriseRentalInformationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        accessEnterpriseRentalInformationLambdaQueryWrapper.in(AccessEnterpriseRentalInformation::getCompanyUuid, companyUuids);
        accessEnterpriseRentalInformationMapper.delete(accessEnterpriseRentalInformationLambdaQueryWrapper);

        // 删除企业信息
        LambdaQueryWrapper<AccessTenantManagement> accessTenantManagementLambdaQueryWrapper = new LambdaQueryWrapper<>();
        accessTenantManagementLambdaQueryWrapper.in(AccessTenantManagement::getCompanyUuid, companyUuids);
        return accessTenantManagementMapper.delete(accessTenantManagementLambdaQueryWrapper);
    }

    /**
     * 获取租户管理列表
     *
     * @param query 入参
     * @return List<TenantManageVO>
     */
    @Override
    public List<TenantManageVO> getTenantManageList(TenantManageQuery query) {
        List<AccessTenantManagement> poList;
        if (!query.getIsAll()) {
            poList = accessTenantManagementMapper.selectByIds(query.getIds());
        } else {
            LambdaQueryWrapper<AccessTenantManagement> lqw = getAccessTenantManagementLambdaQueryWrapper(query);
            poList = accessTenantManagementMapper.selectList(lqw);
        }

        return poList.stream().map(item -> {
            TenantManageVO vo = new TenantManageVO();
            vo.setId(item.getId());
            vo.setCompanyUuid(item.getCompanyUuid());
            vo.setCompanyName(item.getCompanyName());
            vo.setCompanyLegelPerson(item.getCompanyLegelPerson());
            vo.setLegelPersonPhone(item.getLegelPersonPhone());
            vo.setLegelIdCard(item.getLegelIdCard());
            vo.setUnifiedSocialCreditIdentifier(item.getUnifiedSocialCreditIdentifier());
            vo.setAdministrativeContactPerson(item.getAdministrativeContactPerson());
            vo.setAdministrativeContactPersonPhone(item.getAdministrativeContactPersonPhone());
            vo.setIndustryType(item.getIndustryType());
            vo.setMainBusiness(item.getMainBusiness());
            vo.setEstablishedTime(item.getEstablishedTime());
            vo.setBusinessRegistrationAddress(item.getBusinessRegistrationAddress());
            vo.setActualOfficeAddress(item.getActualOfficeAddress());
            vo.setRemark(item.getRemark());
            return vo;
        }).toList();
    }

    /**
     * 导入租户管理模板
     *
     * @param file 文件流
     * @return String
     */
    @Override
    public String importTenantManage(MultipartFile file) {
        // 导入数据
        List<TenantManageVO> dtoList = new ArrayList<>();
        try {
            // 解析文件数据数据
            ExcelResult<TenantManageVO> result = ExcelUtil.importExcel(file.getInputStream(), TenantManageVO.class, true);
            // 获取数据
            dtoList = result.getList();
        } catch (IOException e) {
            log.error(e.toString());
        }
        if (CollectionUtils.isEmpty(dtoList)) {
            log.error("导入数据为空");
            return "";
        }

        // 查询数据
        Map<String, AccessTenantManagement> poMap = new HashMap<>();
        List<AccessTenantManagement> poList = accessTenantManagementMapper.selectList(new QueryWrapper<>());
        if (!CollectionUtils.isEmpty(poList)) {
            poMap = poList.stream().collect(Collectors.toMap(AccessTenantManagement::getCompanyName, po -> po));
        }

        // 新增数据
        List<AccessTenantManagement> insertList = new ArrayList<>();
        // 更新数据
        List<AccessTenantManagement> updateList = new ArrayList<>();

        // 数据处理
        for (TenantManageVO dto : dtoList) {
            AccessTenantManagement po = poMap.get(dto.getCompanyName());
            if (null == po) {
                // 新增
                po = new AccessTenantManagement();
                BeanUtils.copyProperties(dto, po);
                po.setCompanyUuid(IdUtil.randomUUID());
                insertList.add(po);
            } else {
                po.setCompanyLegelPerson(dto.getCompanyLegelPerson());
                po.setLegelPersonPhone(dto.getLegelPersonPhone());
                po.setLegelIdCard(dto.getLegelIdCard());
                po.setUnifiedSocialCreditIdentifier(dto.getUnifiedSocialCreditIdentifier());
                po.setAdministrativeContactPerson(dto.getAdministrativeContactPerson());
                po.setAdministrativeContactPersonPhone(dto.getAdministrativeContactPersonPhone());
                po.setIndustryType(dto.getIndustryType());
                po.setMainBusiness(dto.getMainBusiness());
                po.setEstablishedTime(dto.getEstablishedTime());
                po.setBusinessRegistrationAddress(dto.getBusinessRegistrationAddress());
                po.setActualOfficeAddress(dto.getActualOfficeAddress());
                po.setRemark(dto.getRemark());
                updateList.add(po);
            }
        }

        if (!CollectionUtils.isEmpty(insertList)) {
            accessTenantManagementService.saveBatch(insertList);
        }

        if (!CollectionUtils.isEmpty(updateList)) {
            accessTenantManagementService.updateBatchById(updateList);
        }
        return String.format("新增：%d条，修改：%d条", insertList.size(), updateList.size());
    }

    @Override
    public TenantManageVO detail(Long id) {
        AccessTenantManagement accessTenantManagement = accessTenantManagementMapper.selectById(id);
        TenantManageVO TenantManageVO = new TenantManageVO();
        BeanUtils.copyProperties(accessTenantManagement, TenantManageVO);
        return TenantManageVO;
    }
}
